import DetailContainer, { Title } from "@/components/DetailContainer";
import { add_core, detail_core, edit_core } from "@/services/controller_core";
import { ProForm, ProFormDigit, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { Form, message } from "antd";

const coreMap = {
  add: add_core,
  update: edit_core
};

const UseCoreAddEdit = () => {
  const [form] = Form.useForm();
  const { id } = useParams();
  const isNew = id === "new";

  return (
    <DetailContainer>
      <ProForm
        form={form}
        layout="vertical"
        grid={true}
        rowProps={{
          gutter: [24, 0]
        }}
        request={async () => {
          if (isNew) return {};
          let resp = await detail_core(id as string);
          if (resp.code === 0) {
            return {
              ...resp.data,
              price: Number(resp.data.price)
            };
          } else {
            return {};
          }
        }}
        onFinish={async () => {
          const values = form.getFieldsValue(true);
          if (!isNew) {
            values.id = Number(id);
          }
          const resp = await coreMap[isNew ? "add" : "update"](values);
          if (resp?.code === 0) {
            history.push("/control_core/list");
            message.success(`${isNew ? "新增" : "编辑"}成功`);
          }
        }}
      >
        {/* Core info */}
        <div style={{ width: "100%" }}>
          <Title>Core Info</Title>
        </div>
        <ProFormText
          label="Core name"
          rules={[{ required: true, message: "此项必填" }]}
          name="name"
          colProps={{
            span: 12
          }}
        />

        <ProFormText
          label="Core Models"
          rules={[{ required: true, message: "此项必填" }]}
          name="model"
          colProps={{
            span: 12
          }}
        />

        <ProFormDigit
          label="Code price"
          rules={[{ required: true, message: "此项必填" }]}
          name="price"
          colProps={{
            span: 12
          }}
          placeholder=""
          fieldProps={{
            precision: 2
          }}
        />

        <ProFormText
          label="Core Power"
          rules={[{ required: true, message: "此项必填" }]}
          name="power"
          colProps={{
            span: 12
          }}
        />

        <ProFormText
          label="Core img Url"
          name="core_img"
          colProps={{
            span: 24
          }}
        />

        <ProFormTextArea label="remark" placeholder="" name="remark" />
      </ProForm>
    </DetailContainer>
  );
};

export default UseCoreAddEdit;
